﻿using System.Linq;
using System.Threading.Tasks;
using Microsoft.Phone.BackgroundAudio;
using Microsoft.WindowsAzure.MobileServices;
using WP8DataModel.Model;
using WP8DataModel.ViewModel;

namespace CeskyRozhlasWP8.Model
{
    public class MobileServiceStreamSelector
    {

        public async Task ReinitAsync(int iStationId)
        {

            using (var db = new PlayerAgentDataContext(PlayerAgentViewModel.DefaultDbConnectionString))
            {
                if (db.DatabaseExists() == false)
                {
                    db.CreateDatabase();
                }
                if (db.Streams.Any())
                {
                    //Prevent re-downloading the list.
                    return;
                }

                int id = iStationId;
                var streams = await
                ShowsData.Instance.StreamsTable.Where(stream => stream.Container == "wma").
                Where(stream => stream.Bitrate == 128).
                Where(stream => stream.Stereo).
                OrderBy(stream => stream.StationId).
                ToCollectionAsync();


                var stations = from stream in streams orderby stream.StationId
                    group stream by stream.StationId
                    into g
                    select new {StationId = g.Key, Streams = g.Take(1)};

                foreach (var station in stations)
                {
                    var stream = station.Streams.FirstOrDefault();
                    if (stream != null)
                    {
                        db.Streams.InsertOnSubmit(new StreamDescription
                        {
                            StationId = stream.StationId,
                            Description = stream.Description,
                            ShortName = stream.ShortName,
                            Uri = stream.Uri
                        });
                    }
                }
                db.SubmitChanges();
            }
        }


        public AudioTrack GetStream(int iStationId)
        {
            using (var db = new PlayerAgentDataContext(PlayerAgentViewModel.DefaultDbConnectionString))
            {
                var aCurrentStreamDescription = (from StreamDescription stream in db.Streams
                                                 where stream.StationId == iStationId
                                                 select stream).FirstOrDefault();
                if (aCurrentStreamDescription != null)
                {
                    return aCurrentStreamDescription.AsAudioTrack();
                }
            }
            return null;
        }
    }
}
